﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System.Collections;
using System.Collections.Generic;
using System.Text.Json;
using WebApp.Models;

namespace WebApp
{
    public static class WebServiceEndpoint
    {
        private static string BASE_URL = "api/products";

        public static void MapWebService(this IEndpointRouteBuilder app)
        {
            // 匹配 GET: /api/products/{id}
            app.MapGet($"{BASE_URL}/{{id}}", async context =>
            {
                long key = long.Parse(context.Request.RouteValues["id"] as string);
                DataContext dbContext = context.RequestServices.GetService<DataContext>();

                var p = dbContext.Products.Find(key);
                if (p == null) {
                    context.Response.StatusCode = StatusCodes.Status404NotFound;
                } else {
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = StatusCodes.Status200OK;
                    await context.Response.WriteAsync(JsonSerializer.Serialize<Product>(p));
                }
            });

            app.MapGet(BASE_URL, async context => 
            {
                DataContext dbContext = context.RequestServices.GetService<DataContext>();
                context.Response.ContentType = "application/json";

                await context.Response.WriteAsync(
                    JsonSerializer.Serialize<IEnumerable<Product>>(dbContext.Products));
            });

            app.MapPost(BASE_URL, async context => 
            {
                DataContext dbContext = context.RequestServices.GetService<DataContext>();
                Product p = await JsonSerializer.DeserializeAsync<Product>(context.Request.Body);
                await dbContext.AddAsync(p);
                await dbContext.SaveChangesAsync();

                context.Response.StatusCode=StatusCodes.Status200OK;
            });
        }
    }
}
